import * as fs from 'fs';
import * as path from 'path';

/**
 * 模型选择器 - 根据任务类型智能选择最合适的 LLM
 */
export class ModelSelector {
    private static selectionConfig: any = null;

    /**
     * 加载模型选择配置
     */
    private static loadConfig(): any {
        if (this.selectionConfig) {
            return this.selectionConfig;
        }

        try {
            const possiblePaths = [
                path.join(__dirname, 'llm-selection-config.json'),
                path.join(__dirname, '..', 'llm-selection-config.json'),
                path.join(__dirname, '..', 'core', 'llm-selection-config.json')
            ];

            let configPath = '';
            for (const tryPath of possiblePaths) {
                if (fs.existsSync(tryPath)) {
                    configPath = tryPath;
                    break;
                }
            }

            if (!configPath) {
                console.warn('[ModelSelector] llm-selection-config.json not found, using default');
                return this.getDefaultConfig();
            }

            const configData = fs.readFileSync(configPath, 'utf-8');
            this.selectionConfig = JSON.parse(configData);
            return this.selectionConfig;
        } catch (error) {
            console.error('[ModelSelector] Error loading config:', error);
            return this.getDefaultConfig();
        }
    }

    /**
     * 默认配置
     */
    private static getDefaultConfig(): any {
        return {
            defaultModel: 'glm-4-flash',
            modelSelection: {
                fuzzTest: {
                    primary: 'qwen-plus',
                    fallback: ['glm-4-flash']
                },
                unitTest: {
                    primary: 'qwen-max',
                    fallback: ['glm-4-flash']
                }
            }
        };
    }

    /**
     * 根据任务类型选择模型
     * @param taskType 任务类型: 'fuzzTest' | 'unitTest' | 'codeReview' | 'general'
     * @param preferredModel 用户偏好模型（可选）
     * @returns 模型名称
     */
    public static selectModel(
        taskType: 'fuzzTest' | 'unitTest' | 'codeReview' | 'general' = 'general',
        preferredModel?: string
    ): string {
        const config = this.loadConfig();

        // 如果用户指定了偏好模型，优先使用
        if (preferredModel) {
            console.log(`[ModelSelector] Using user-preferred model: ${preferredModel}`);
            return preferredModel;
        }

        // 根据任务类型选择
        const taskConfig = config.modelSelection[taskType];
        if (taskConfig && taskConfig.primary) {
            console.log(`[ModelSelector] Selected ${taskConfig.primary} for ${taskType}`);
            return taskConfig.primary;
        }

        // 降级到默认模型
        console.log(`[ModelSelector] Using default model: ${config.defaultModel}`);
        return config.defaultModel;
    }

    /**
     * 获取任务的备用模型列表
     * @param taskType 任务类型
     * @returns 备用模型列表
     */
    public static getFallbackModels(
        taskType: 'fuzzTest' | 'unitTest' | 'codeReview' | 'general'
    ): string[] {
        const config = this.loadConfig();
        const taskConfig = config.modelSelection[taskType];
        return taskConfig?.fallback || [config.defaultModel];
    }

    /**
     * 获取所有可用的模型列表
     */
    public static getAvailableModels(): string[] {
        const config = this.loadConfig();
        return Object.keys(config.modelProfiles || {});
    }

    /**
     * 获取模型详细信息
     */
    public static getModelProfile(modelName: string): any {
        const config = this.loadConfig();
        return config.modelProfiles?.[modelName] || null;
    }

    /**
     * 打印模型选择建议
     */
    public static printModelRecommendations(): void {
        const config = this.loadConfig();
        console.log('\n=== LLM 模型选择建议 ===\n');

        for (const [taskType, taskConfig] of Object.entries(config.modelSelection)) {
            const tc = taskConfig as any;
            console.log(`📌 ${taskType}:`);
            console.log(`   主选: ${tc.primary}`);
            console.log(`   备选: ${tc.fallback?.join(', ')}`);
            console.log(`   说明: ${tc.description}`);
            console.log('');
        }

        console.log('=== 模型性能对比 ===\n');
        for (const [modelName, profile] of Object.entries(config.modelProfiles)) {
            const p = profile as any;
            console.log(`🔹 ${modelName}:`);
            console.log(`   类型: ${p.type}`);
            console.log(`   优势: ${p.strengths?.join(', ')}`);
            console.log(`   速度: ${p.speed} | 成本: ${p.cost}`);
            console.log('');
        }
    }
}

